import express, { Request, Response, RequestHandler, NextFunction } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { errorHandler } from './middleware/errorHandler';
import { responseFormatter } from './middleware/responseFormatter';
import circleRoutes from './routes/circleRoutes';
import uploadRoutes from './routes/uploadRoutes'; // 导入上传路由
import User from './models/User'; // 导入 User 模型
import InterestTag from './models/InterestTag'; // 导入 InterestTag 模型
import bcrypt from 'bcryptjs'; // 导入 bcrypt
import jwt from 'jsonwebtoken'; // 导入 jsonwebtoken
import { connectDB } from './config/database'; // 导入连接数据库函数
import { JWT_SECRET } from './config/constants';

dotenv.config();

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 响应格式化中间件
app.use(responseFormatter);

// 从 'uploads' 目录提供静态文件
app.use('/uploads', express.static('uploads'));

// 认证中间件
const authenticateToken: RequestHandler = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (token == null) {
        res.sendStatus(401); // 如果没有任何 token
        return; // 明确返回 undefined
    }

    jwt.verify(token, JWT_SECRET, (err: any, user: any) => {
        if (err) {
            console.error('JWT verification error:', err);
            res.sendStatus(403); // 如果 token 不再有效
            return; // 明确返回 undefined
        }
        // @ts-ignore: 向请求对象添加用户信息
        (req as any).user = user;
        next(); // 调用 next() 将控制权传递给下一个中间件/处理程序
    });
};

// 根路由
app.get('/', (req: Request, res: Response) => {
    res.send('Backend is running!');
});

// 用户认证路由处理函数
// @ts-ignore
const registerHandler: RequestHandler = async (req: Request, res: Response) => {
    console.log('Received request body:', req.body);
    console.log('Content-Type:', req.headers['content-type']);

    const { username, email, password, gender, avatar } = req.body;

    try {
        // 检查用户是否已存在
        const existingUser = await User.findOne({ where: { username } });
        if (existingUser) {
            return res.status(400).json({ success: false, message: 'Username already exists' });
        }

        // 检查邮箱是否已存在
        const existingEmail = await User.findOne({ where: { email } });
        if (existingEmail) {
            return res.status(400).json({ success: false, message: '邮箱已被注册' });
        }

        // 创建包含所有收集字段的新用户
        const newUser = await User.create({ username, email, password, gender, avatar });

        // 返回成功响应（不包含密码）
        const userResponse = { ...newUser.toJSON() };
        delete (userResponse as any).password;
        res.status(201).json({ success: true, message: 'User registered successfully', user: userResponse });

    } catch (error: any) {
        console.error('Registration error:', error);
        res.status(500).json({ success: false, message: error.message || 'Server error' });
    }
};

// @ts-ignore
const loginHandler: RequestHandler = async (req: Request, res: Response) => {
    console.log('Received login request body:', req.body);
    console.log('Login Content-Type:', req.headers['content-type']);

    const { username, password } = req.body;

    try {
        // 按用户名查找用户
        const user = await User.findOne({ where: { username } });
        if (!user) {
            return res.status(400).json({ success: false, message: '用户不存在' });
        }

        // 比较提供的密码和哈希密码
        const isMatch = await user.comparePassword(password);
        if (!isMatch) {
            return res.status(400).json({ success: false, message: '密码错误' });
        }

        // 生成 JWT token
        const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '7d' }); // 使用 .env 中的 JWT_SECRET，有效期设置为 7 天

        // 返回包含用户信息（不包含密码）和 token 的响应
        const userResponse = { ...user.toJSON() };
        delete (userResponse as any).password;
        res.json({ success: true, user: userResponse, token });

    } catch (error: any) {
        console.error('Login error:', error);
        res.status(500).json({ success: false, message: error.message || '服务器错误' });
    }
};

// 新的用户资料路由处理函数 - 受认证中间件保护
// @ts-ignore
const getUserProfileHandler: RequestHandler = async (req: Request, res: Response) => {
    try {
        // @ts-ignore
        const userId = (req as any).user.userId; // 从认证 token 中获取用户 ID
        const user = await User.findByPk(userId, {
            attributes: { exclude: ['password'] }, // 排除密码
            include: [{
                model: InterestTag,
                as: 'interestTags',
                through: { attributes: [] } // 不包含中间表属性
            }]
        });

        if (!user) {
            return res.status(404).json({ success: false, message: 'User not found' });
        }

        res.json({ success: true, user: user.toJSON() });

    } catch (error: any) {
        console.error('Get user profile error:', error);
        res.status(500).json({ success: false, message: error.message || 'Server error' });
    }
};

// @ts-ignore
const updateUserProfileHandler: RequestHandler = async (req: Request, res: Response) => {
    console.log('Update profile request body:', req.body);
    const { username, email, avatar, gender, age, birthDate, zodiacSign, location, interestTags, bio } = req.body;

    try {
        // @ts-ignore
        const userId = (req as any).user.userId; // 从认证 token 中获取用户 ID
        const user = await User.findByPk(userId);

        if (!user) {
            return res.status(404).json({ success: false, message: 'User not found' });
        }

        // 如果请求体中提供了用户字段，则更新
        if (username !== undefined) user.username = username;
        if (email !== undefined) user.email = email;
        if (gender !== undefined) user.gender = gender;
        if (age !== undefined) user.age = age;
        if (birthDate !== undefined) user.birthDate = birthDate;
        if (zodiacSign !== undefined) user.zodiacSign = zodiacSign;
        if (location !== undefined) user.location = location;
        if (bio !== undefined) user.bio = bio;
        if (avatar !== undefined) user.avatar = avatar; // 添加 avatar 更新逻辑

        // 保存基本用户信息
        await user.save();

        // 如果提供了兴趣标签，更新关联
        if (interestTags !== undefined) {
            // 先清除现有的兴趣标签关联
            const currentTags = await user.getInterestTags();
            for (const tag of currentTags) {
                await user.removeInterestTag(tag);
            }
            // 如果有新的兴趣标签，添加它们
            if (Array.isArray(interestTags) && interestTags.length > 0) {
                for (const tagId of interestTags) {
                    const tag = await InterestTag.findByPk(tagId);
                    if (tag) {
                        await user.addInterestTag(tag);
                    }
                }
            }
        }

        // 获取更新后的用户信息，包括兴趣标签
        const updatedUser = await User.findByPk(userId, {
            include: [{
                model: InterestTag,
                as: 'interestTags'
            }],
            attributes: { exclude: ['password'] }
        });

        // Respond with updated user info (excluding password)
        const userResponse = updatedUser?.toJSON();
        res.json({ success: true, message: 'User profile updated successfully', user: userResponse });

    } catch (error: any) {
        console.error('Update user profile error:', error);
        res.status(500).json({ success: false, message: error.message || 'Server error' });
    }
};

// Get all tags route处理函数
const getAllTagsHandler: RequestHandler = async (req: Request, res: Response) => {
    try {
        const tags = await InterestTag.findAll();
        res.json({ success: true, tags });
    } catch (error: any) {
        console.error('Get tags error:', error);
        res.status(500).json({ success: false, message: error.message || 'Server error' });
    }
};

// 注册认证路由
app.post('/api/auth/register', registerHandler);
app.post('/api/auth/login', loginHandler);
app.get('/api/auth/me', authenticateToken, getUserProfileHandler);
app.put('/api/auth/me', authenticateToken, updateUserProfileHandler);

// 注册上传路由
app.use('/api/upload', uploadRoutes);

// 注册圈子相关路由
app.use('/api/circles', circleRoutes); // 确保圈子路由被正确注册

// 注册标签路由
app.get('/api/tags', getAllTagsHandler); // 添加标签路由注册

// 错误处理中间件
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
    errorHandler(err, req, res, next);
});

// 404 处理
app.use((req: Request, res: Response) => {
    res.error('请求的资源不存在', 404);
});

export default app; 